layui.define(function(a) {
    var c = layui.jquery;
    var n = layui.table,
        e = layui.flow;
    var s = layui.form,
        d = layui.admin.lang;
    var l = "aHR0cHM6Ly9hcGkuc3dpZnRhZG1pbi5uZXQ=";
    var i = window.location.href.split("://")[1],
        t = i.indexOf("/"),
        r = i.indexOf(".php") + 4,
        u = i.substring(t, r),
        o = [c(window).width() > 800 ? "660px" : "85%", c(window).height() > 800 ? "680px" : "85%"];
    var y = {
        apiUrl: window.atob(l),
        install: function(s, a, n) {
            c.post(u + n, {
                name: s,
                token: a
            }, function(a) {
                layer.closeAll();
                if (a.code == 200) {
                    top.layui.iziToast.success({
                        message: a.msg
                    });
                    var e = layui.sessionData("api_install_index").index,
                        l = c('tr[data-index="' + e + '"]');
                    if (n.indexOf("install") != -1) {
                        var i = "",
                            t = '<input type="checkbox" lay-filter="switchStatus" lay-url="';
                        t += u + '/system.plugin/status" value="' + s + '" lay-skin="switch" checked="">';
                        t += '<div class="layui-unselect layui-form-switch layui-form-onswitch" lay-skin="_switch"><em></em><i></i></div>';
                        c(l).find('[data-field="status"]').children("div").append(t);
                        data = a.data || [];
                        if (data.config) {
                            i += '<a class="layui-table-text" lay-title="' + d("配置插件") + '"';
                            i += 'lay-area="' + data.area + '" lay-maxmin="true"';
                            i += 'lay-url="' + u + "/system.plugin/config/name/" + s + '" ';
                            i += 'lay-event="edit">' + d("配置") + "</a>";
                            i += '<div class="layui-divider layui-divider-vertical"></div> '
                        }
                        i += '<a class="layui-table-text uninstall" style="color:red"';
                        i += 'lay-url="' + u + "/system.plugin/uninstall/name/" + s + '">' + d("卸载") + "</a> ";
                        c(l).find("td:last").children("div").html(i);
                        window.plugins[s] = a.data
                    } else {
                        l.find(".layui-upgrade-elem").remove();
                        l.find(".layui-form-switch").addClass("bubble");
                        l.find(".layui-form-switch").trigger("click", ["stopPropagation"])
                    }
                    layui.admin.saPHPInit(true)
                } else {
                    top.layui.iziToast.error({
                        message: a.msg
                    });
                    if (a.code == -101) {
                        y.login();
                        return false
                    }
                    if (a.code == -102) {
                        y.pay(a.data);
                        return false
                    }
                }
            }, "json")
        },
        login: function() {
            layer.open({
                type: 1,
                title: "登录",
                shadeClose: true,
                area: ["500px", "350px"],
                content: y.getHtml(),
                success: function(a, e) {
                    s.on("submit(login)", function(a) {
                        c.post(y.apiUrl + "/user/login", a.field, function(a) {
                            if (a.code == 200) {
                                layui.admin.setStorage("api_cross_token", a.data.token);
                                layer.closeAll();
                                y.againclick()
                            } else {
                                top.layui.iziToast.error({
                                    message: a.msg
                                })
                            }
                        }, "json");
                        return false
                    })
                }
            })
        },
        clearLogin: function() {
            layui.admin.setStorage("api_cross_token", null)
        },
        pay: function(a) {
            layer.open({
                type: 2,
                title: d("立即支付"),
                area: o,
                offset: "30px",
                resize: false,
                shade: .8,
                shadeClose: true,
                content: a.payurl,
                success: function(a, l) {
                    window.onmessage = function(a) {
                        var e = a.data;
                        if (a.data !== null && e.code == 200) {
                            layer.close(l);
                            y.againclick()
                        }
                        if (a.data !== null && e.code == -133) {
                            layer.close(l)
                        }
                    }
                }
            })
        },
        againclick: function() {
            try {
                var a = layui.sessionData("api_install_index").index,
                    e = c('tr[data-index="' + a + '"]').children().find(".install");
                if (e.length <= 0) {
                    e = c('[layui-value="' + a + '"]')
                }
                if (e && a != null) {
                    c(e).trigger("click")
                }
            } catch (a) {
                console.log(a)
            }
        },
        uninstall: function(s, a) {
            c.post(u + y.getUrl("plugin", "uninstall"), {
                name: s,
                tables: a
            }, function(a) {
                if (a.code == 200) {
                    top.layui.iziToast.success({
                        message: a.msg,
                        onClose: function() {}
                    });
                    var e = layui.sessionData("api_install_index").index,
                        l = c('tr[data-index="' + e + '"]');
                    c(l).find('[data-field="status"]').children("div").html("");
                    var i = '<a class="layui-table-text install" lay-url="' + u;
                    i += "/system.plugin/install/name/" + s + '">' + d("安装") + "</a>";
                    var t = n.cache["lay-tableList"][e];
                    if (typeof t.demourl != "undefined") {
                        i += '<div class="layui-divider layui-divider-vertical"></div>';
                        i += '<a class="layui-table-text" target="_blank" href="';
                        i += t.demourl + '">' + d("演示") + "</a>"
                    }
                    delete window.plugins[s];
                    c(l).find("td:last").children("div").html(i);
                    layui.admin.saPHPInit(true)
                } else {
                    top.layui.iziToast.error({
                        message: a.msg
                    })
                }
                layer.closeAll()
            }, "json")
        },
        getUrl(a, e) {
            return "/system." + a + "/" + e
        },
        getTableData: function(a) {
            if (a == null || a == "undefined") {
                return false
            }
            var e = c(a).parents("tr").attr("data-index");
            e = n.cache["lay-tableList"][e];
            return e
        },
        getHtml: function() {
            var a = '<form class="layui-form layui-form-fixed" style="padding-right:15px;" >';
            a += '<blockquote class="layui-elem-quote layui-elem-plugin">温馨提示<br/>';
            a += '此处登录为 <a href="//www.panda.net" target="_blank" class="website">Panda云平台账号</a>';
            a += '</blockquote><div style="height:20px;"></div>';
            a += '<div class="layui-form-item">';
            a += '<label class="layui-form-label">用户帐号</label>';
            a += '<div class="layui-input-block">';
            a += '<input type="text" name="name" style="width:330px;" lay-verify="required" placeholder="请输入帐号" class="layui-input" >';
            a += "</div></div>";
            a += '<div class="layui-form-item"><label class="layui-form-label">密码</label>';
            a += '<div class="layui-input-block">';
            a += '<input type="password" name="pwd" style="width:330px;" lay-verify="required" placeholder="请输入密码" class="layui-input">';
            a += "</div></div>";
            a += '<div class="layui-form-item" style="margin-top: 22px;text-align: center;">';
            a += '<button type="submit" class="layui-btn layui-btn-normal" lay-submit lay-filter="login">登录</button>';
            a += '<a class="layui-btn layui-btn-primary" href="http://www.panda.net/user/register.html" target="_blank">注册账号</a>';
            a += "</div></form> ";
            return a
        }
    };
    c(".layui-plugin-select").click(function(a) {
        var e = c(this);
        if (e.hasClass("active") && !e.hasClass("first")) {
            e.removeClass("active");
            e.siblings("span.first").addClass("active")
        } else {
            e.siblings(".active").removeClass("active");
            e.addClass("active")
        }
        var t = {},
            l = c(".active");
        l.each(function(a, e) {
            var l = c(e).attr("lay-value") || "",
                i = c(e).parent().attr("name");
            t[i] = l
        });
        var i = ["type", "pay", "label"];
        for (let a in i) {
            if (!t[i[a]]) {
                t[i[a]] = ""
            }
        }
        n.reload("lay-tableList", {
            where: t,
            url: y.apiUrl + "/plugin/index"
        })
    });
    c(document).on("click", ".install,.upgrade", function(a) {
        var e = c(this),
            l = layer.load(),
            i = e.attr("class"),
            t = e.attr("lay-type") || "plugin",
            s = i.replace("layui-table-text", "").replace(/(^\s*)|(\s*$)/g, ""),
            n = y.getTableData(this)["name"],
            r = layui.admin.getStorage("api_cross_token") || null;
        layui.sessionData("api_install_index", {
            key: "index",
            value: y.getTableData(this)["LAY_TABLE_INDEX"]
        });
        if (r == null || r == "undefined") {
            layer.close(l);
            y.login();
            return false
        }
        if (s.indexOf("upgrade") != -1) {
            var u = '确认升级《<font size="4">' + n + "</font>》插件？<br/>";
            u += '<font color="red">1、请务必做好代码和数据库备份！</font><br/>';
            u += '<font color="red">2、升级后如出现冗余数据，请根据需要移除即可！</font><br/>';
            u += '<font color="red">3、生产环境下更新插件，请勿在流量高峰期操作！</font><br/>';
            var o = layer.confirm(u, {
                title: d("更新提示")
            }, function() {
                layer.close(o);
                y.install(n, r, y.getUrl(t, s))
            }, function() {
                layer.close(l)
            })
        } else {
            y.install(n, r, y.getUrl(t, s))
        }
    });
    s.on("switch(pluginStatus)", function(e) {
        var a = c(this),
            l = {
                error: function(a) {
                    c(e.elem).prop("checked", !e.elem.checked);
                    s.render("checkbox");
                    layui.iziToast.error({
                        message: a.msg
                    })
                },
                success: function(a) {
                    layui.iziToast.success({
                        message: a.msg
                    });
                    window.plugins[i.id].status = i.status;
                    layui.admin.saPHPInit(true)
                }
            },
            i = {
                id: c(this).attr("value"),
                status: e.elem.checked ? 1 : 0
            };
        if (c(".bubble").length) {
            c(".bubble").removeClass("bubble");
            return false
        }
        layui.admin.event.ajax(a, i, l)
    });
    c(document).on("click", ".uninstall", function(a) {
        var t = y.getTableData(this)["name"];
        var e = '<form class="layui-form layui-form-fixed" style="padding-right:15px;" >';
        e += '<blockquote class="layui-elem-quote layui-elem-plugin">温馨提示<br/>';
        e += "确认卸载 《" + t + "》 吗？<br/>";
        e += "1、卸载前请自行备份插件数据库 ！<br/>";
        e += "2、插件文件及数据库表删除后无法找回 ！<br/>";
        e += "3、插件如已被二次开发，请自行清除冗余文件！<br/>";
        e += "</blockquote>";
        e += '<div class="layui-form-item">';
        e += '<div class="layui-input-inline" style="padding-left: 5px;">';
        e += '<input type="checkbox" lay-filter="tables" lay-skin="primary" title="删除插件相关数据库表" >';
        e += '<div class="layui-plugin-tables layui-badge-red"></div></div></div>';
        e += '<div class="layui-footer" style="margin-top: 22px;text-align: center;">';
        e += '<button type="submit" class="layui-btn layui-btn-normal" lay-submit lay-filter="start">确定</button>';
        e += '<button type="button" class="layui-btn layui-btn-primary" pa-event="closeDialog" >关闭</button>';
        e += "</div></form> ";
        layui.sessionData("api_install_index", {
            key: "index",
            value: y.getTableData(this)["LAY_TABLE_INDEX"]
        });
        layer.open({
            type: 1,
            title: d("卸载插件"),
            shadeClose: true,
            area: ["380px", "360px"],
            content: e,
            success: function(a, i) {
                s.render();
                s.on("checkbox(tables)", function(a) {
                    if (a.elem.checked) {
                        c.get(u + "/system.plugin/tables", {
                            name: t
                        }, function(a) {
                            try {
                                if (a.code == 200 && a.data.tables) {
                                    var e = [];
                                    var l = "<span>即将删除数据表：</span>";
                                    c(".layui-plugin-tables").append(l).show();
                                    for (var i in a.data.tables) {
                                        e.push([a.data.tables[i]]);
                                        var t = "<span>" + a.data.tables[i] + "</span>、";
                                        c(".layui-plugin-tables").append(t)
                                    }
                                } else {
                                    top.layui.iziToast.error({
                                        message: a.msg
                                    })
                                }
                            } catch (a) {
                                console.log(a)
                            }
                        }, "json")
                    } else {
                        c(".layui-plugin-tables").html("").hide()
                    }
                });
                s.on("submit(start)", function(a) {
                    var l = [];
                    var e = c(".layui-plugin-tables").children("span");
                    e.each(function(a, e) {
                        if (a >= 1) {
                            l.push(c(e).html())
                        }
                    });
                    layer.load();
                    layer.close(i);
                    y.uninstall(t, l);
                    return false
                })
            }
        })
    });
    c("*[lay-value=install]").click(function(a) {
        n.reload("lay-tableList", {
            url: u + "/system.plugin/index?type=install"
        })
    });
    c("*[lay-value=cache]").click(function(a) {
        var e = layer.confirm("确定要更新缓存吗？", {
            title: "更新提示"
        }, function() {
            c.get(u + y.getUrl("admin", "clear/type/plugin"), {}, function(a) {
                if (a.code == 200) {
                    layui.iziToast.success({
                        message: a.msg
                    });
                    layer.close(e)
                }
            })
        })
    });
    c("body").on("click", ".layui-icon-picture", function(a) {
        var e = y.getTableData(this),
            l = [];
        if (e.album) {
            for (let a in e.album) {
                l.push({
                    src: e.album[a].src,
                    thumb: e.album[a].src
                })
            }
        }
        layer.photos({
            photos: {
                data: l
            },
            shadeClose: true,
            closeBtn: 2,
            anim: 10
        })
    });
    a("plugin", y)
});